﻿using System;

namespace ECommerce.Administration.Controls
{
	public partial class EditNews : AdminBaseUsercontrol
	{
		private int _NewsID;
		private Service.INewsService _NewsService;

		public int NewsID
		{
			get
			{
				if(ViewState["NewsID"] != null)
				{
					_NewsID = int.Parse(ViewState["NewsID"].ToString());
				}
				else
				{
					_NewsID = CommonHelper.QueryStringInt("newsid");
				}
				return _NewsID;
			}
			set
			{
				_NewsID = value;
				ViewState["NewsID"] = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				if (NewsID > 0)
				{
					LabelEditNewsTitle.Text = GetLocalResourceString("Admin.EditNews.Edit.Title");
				}
				else
				{
					LabelEditNewsTitle.Text = GetLocalResourceString("Admin.EditNews.Add.Title");
				}

				ButtonSave.Text = GetLocalResourceString("Admin.SaveButtonText");
				
				SetValues();
			}
		}

		protected void ButtonSave_Click(object sender, EventArgs e)
		{
			if (SiteContext.Current.WorkingLanguage != null)
			{
				var theNews = new Data.Entity.News();

				if (_NewsService == null)
				{
					_NewsService = new Service.NewsService();
				}

				theNews.AllowComments = false;
				theNews.CreatedOn = DateTime.Now;
				theNews.FullContent = EditorFullContent.Content;
				theNews.LanguageID = SiteContext.Current.WorkingLanguage.LanguageId;
				theNews.Published = CheckPublished.Checked;
				theNews.ShortContent = TextShortContent.Text.Trim();
				theNews.Title = TextNewsTitle.Text.Trim();

				if (NewsID > 0)
				{
					theNews.NewsID = NewsID;
					_NewsService.UpdateNews(theNews);
				}
				else
				{
					NewsID = _NewsService.CreateNews(theNews);
				}
			}
		}

		private void SetValues()
		{
			if(NewsID > 0)
			{
				if (_NewsService == null)
				{
					_NewsService = new Service.NewsService();
				}
				
				var theNews = _NewsService.GetTheNews(NewsID);

				if(theNews != null)
				{
					TextNewsTitle.Text = theNews.Title;
					TextShortContent.Text = theNews.ShortContent;
					EditorFullContent.Content = theNews.FullContent;
					CheckPublished.Checked = theNews.Published;
				}
			}
		}
	}
}